/*
 * Copyright (c) 2020 Fraunhofer FOKUS and others. All rights reserved.
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contact: mosaic@fokus.fraunhofer.de
 */
package org.eclipse.mosaic.lib.objects.traffic;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.eclipse.mosaic.lib.objects.UnitData;
import org.eclipse.mosaic.lib.objects.vehicle.VehicleData;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MecDetectorInfo extends UnitData {

    private static final long serialVersionUID = 1L;

    private static final AtomicLong idGenerator = new AtomicLong(0);

    private static final Map<String, Long> name2MecId = new HashMap<>();

    private final List<VehicleData> vehicles;

    public MecDetectorInfo(
            long time,
            String name,
            List<VehicleData> vehicles) {
        super(time, name, null);
        this.vehicles = vehicles;
        flush();
    }

    public void flush() {
        for (VehicleData vehicle : vehicles) {
            String name = vehicle.getName();
            if (!name2MecId.containsKey(name)) {
                long id = idGenerator.getAndIncrement();

                name2MecId.put(name, id);
            }
        }
    }

    public Map<Long, VehicleData> getVehicles() {
        return vehicles.stream()
                .collect(Collectors.toMap(e -> name2MecId.get(e.getName()), Function.identity(), (e1, e2) -> e1));
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }

        MecDetectorInfo other = (MecDetectorInfo) obj;
        return new EqualsBuilder()
                .appendSuper(super.equals(other))
                .append(this.name2MecId, other.name2MecId)
                .append(this.vehicles, other.vehicles)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(7, 29)
                .append(super.hashCode())
                .append(name2MecId)
                .append(vehicles)
                .toHashCode();
    }

    public String toString() {
        return "MecDetectorInfo{"
                + "name=" + super.getName()
                + ", name2MecId=" + name2MecId
                + ", vehicles=" + vehicles + '}';
    }
}
